<template>
  <div>
    <el-card shadow="always" v-loading="loading" element-loading-text="数据加载中..." element-loading-background="rgba(256, 256, 256, 0.8)">
      <el-form :model="form" status-icon ref="form" label-width="100px" @submit.native.prevent v-loading="loading" :inline="true">
        <el-form-item label="审批人" >
          <el-input size="mini" v-model="form.user" placeholder="审批人" ></el-input>
        </el-form-item>
        <el-form-item label="审批人" >
          <el-input size="mini" v-model="form.user" placeholder="审批人" ></el-input>
        </el-form-item>
        <el-form-item label="审批人" >
          <el-input size="mini" v-model="form.user" placeholder="审批人" ></el-input>
        </el-form-item>
        <el-form-item label="活动区域">
          <el-select v-model="form.region" placeholder="活动区域" size="mini" >
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker v-model="form.datetime" type="datetime" placeholder="选择日期时间" format='yyyy-MM-dd'></el-date-picker>
        </el-form-item>
        <el-form-item label="时间1">
          <el-date-picker v-model="form.datetime1" type="datetime" placeholder="选择日期时间" popper-class="datepickerPopperClass"
          value-format="yyyy-MM-dd H"
          format="yyyy-MM-dd H"  @change="pickChange"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <!--          multiple-->
          <el-select v-model="form.value1" placeholder="请选择" @change="changeIdentify">
            <el-option v-for="(item,index) in options" :key="index" :label="item.value" :value="item.i.j.v" >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="submit">
          <el-button @click="submitForm('form')" type="primary" size="mini">保存</el-button>
          <el-button @click="resetForm('form')" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
      <div style="background-color: #FAFAFA">
        <!-- <el-button type="primary" class="invoicing" @click="automaticInvoice" :disabled="automaticButton"> 一键开票
        </el-button> -->
        <span class="button-desc">（一键开票功能在勾选需要开票的用户后开放！）</span>
        <el-button type="primary" plain @click="AddRow" size="small " icon="el-icon-circle-plus-outline" style="margin: 10px 0px 10px;">添加一行</el-button>
        <el-button type="danger" plain @click="DeleteTableDataFun" size="small " icon="el-icon-delete">删除</el-button>
        <el-button type="success" plain @click="SaveData" size="small " icon="el-icon-document-checked">保存</el-button>
        <!-- stripe 斑马纹表格 -->
        <!-- border 带边框表格 -->
        <!-- @selection-change 复选框选择事件 -->
        <!-- @row-dblclick 行上双击事件 -->
        <!-- show-summary 表底的合计 -->
        <el-form :disabled="false">
        <el-table ref="Table" :data="tableDataSearch" @selection-change="SelectFun" @row-dblclick="RowDblclick" @row-click="RowClick" show-summary :summary-method="getSummaries" stripe border @header-click="HeaderClick" @select-all="handleSelectAll">
          <el-table-column type="selection" align="center" width="60px" disabled></el-table-column>
          <!-- type="index" 自动编号 序号 -->
          <!-- <el-table-column type="index" label="序号" align="center" width="60px"></el-table-column> -->
          <el-table-column type="index" label="序号" align="center" width="60px">
            <template slot-scope="scope">
              {{scope.row.index+1}}
            </template>
          </el-table-column>
          <el-table-column label="地址" width="250px" show-overflow-tooltip>
            <template slot="header">
              <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
            </template>
            <template slot-scope="scope">
              <el-input v-show="doubleclick==scope.row.line" type="text" placeholder="请输入地址" v-model="scope.row.address" size="mini" prefix-icon="el-icon-edit" clearable>
              </el-input>
              <span v-show="doubleclick!=scope.row.line">{{scope.row.address}}</span>
            </template>
          </el-table-column>
          <el-table-column label="日期1" width="170" sortable align="center">
            <template slot-scope="scope">
              <!-- <el-date-picker v-show="doubleclick==scope.row.line" v-model="scope.row.date" format="yyyy-MM-dd" align="center" type="date" placeholder="选择日期" size="mini" style="width: 58%;">
              </el-date-picker> -->
              <span>{{DateFormats(scope.row.date)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="年龄" prop="age" width="70" align="center"></el-table-column>
          <el-table-column label="数值" prop="num" align="right">
            <template slot-scope="scope">
              <el-input v-show="doubleclick==scope.row.line" type="Number" placeholder="请输入内容" v-model.number="scope.row.num" size="mini" clearable>
              </el-input>
              <span v-show="doubleclick!=scope.row.line">{{scope.row.num}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="145px" align="center" fixed="right">
            <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                下拉菜单<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>黄金糕</el-dropdown-item>
                <el-dropdown-item>狮子头</el-dropdown-item>
                <el-dropdown-item>螺蛳粉</el-dropdown-item>
                <el-dropdown-item disabled>双皮奶</el-dropdown-item>
                <el-dropdown-item divided>蚵仔煎</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
              <!-- slot-scope="scope" 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据-->
              <el-button size="mini" plain type="primary" @click="HandleEdit(scope.$index, scope.row)" style="margin: 4px;">详情</el-button>
              <el-popover trigger="click" placement="top" width="160" clearable :key="scope.row.age">
                <p>是否确认删除</p>
                <div align="center">
                  <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="DeleteData(scope.$index, tableData)"></el-button>
                </div>
                <!-- slot="reference" 触发 Popover 的元素,使用 slot="reference" 的具名插槽 -->
                <el-button size="mini" plain type="danger" slot="reference">删除</el-button>
              </el-popover>
              <!--  -->
              <!-- <div class="btn" v-for="(btn, index) in buttonList" :key="index">
                <el-button :type="btn.type" @click="btnEvent(btn.btnEvent,index)" :icon="btn.icon">
                  {{btn.name}}
                </el-button>
              </div> -->
            </template>

          </el-table-column>

        </el-table>
        </el-form>

        <div class="block" align="right">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
const addItem = (item) => {
  console.log(123, item);
  //...
};
const deleteItem = () => {
  //...
};
export default {
  name: "template-table",
  props: {
    tableData: Array,
    type: Boolean,
  },
  data() {
    return {
      pickerOptions:{

      },
      //定义按钮
      buttonList: [
        {
          type: "primary",
          name: "新增",
          btnEvent: "addItem()",
          icon: "Plus",
        },
        {
          type: "danger",
          name: "删除",
          btnEvent: "deleteItem()",
          icon: "Delete",
        },
      ],
      options: [
        {
          i: {
            j: {
              v: "111",
            },
          },
          value: "选项1",
          label: "黄金糕",
        },
        {
          i: {
            j: {
              v: "222",
            },
          },
          value: "选项2",
          label: "双皮奶",
        },
        {
          i: {
            j: {
              v: "333",
            },
          },
          value: "选项3",
          label: "双皮奶",
        },
        {
          i: {
            j: {
              v: "444",
            },
          },
          value: "选项4",
          label: "双皮奶",
        },
      ],
      value1: [],
      form: {},
      search: "",
      doubleclick: null, // 记录当前编辑行序号
      deleteTableData: [], // 记录所有标记删除的数据 暂无用
      selectList: [], // 记录本次批量选择的数据
      // tableData: [], // datable的数据
      loading: false, // 加载是否转圈圈
      currentPage: 1, // 当前页码
      value: [],
      // options: [],
      props: {
        emitPath: false, //若设置 false，则只返回该节点的值
        multiple: false, //多选模式
        expandTrigger: "hover", //定义展开子级菜单的触发方式。
        checkStrictly: true, //父子节点取消选中关联，从而达到选择任意一级选项的目的
      },
    };
  },
  mounted() {

    this.loading = true;
    setTimeout(() => {
      // this.form = {
      //   value1: "111",
      // };
      this.form.value1 = '222'
      this.initdata();
      this.loading = false;
    }, 1000);
  },
  watch: {
    type(newVal, oldVal) {
      console.log(newVal);
      // this.$message(newVal,oldVal)
    },
    // search(val) {
    //   this.tableData = this.tableData.filter(
    //     (data) => !val || data.name.toLowerCase().includes(val.toLowerCase())
    //   );
    // },
  },
  computed: {
    tableDataSearch() {
      return this.tableData.filter(
        (data) =>
          !this.search ||
          data.name.toLowerCase().includes(this.search.toLowerCase())
      );
    },
    // 动态样式，利用必报解决不能传参的问题
    styleObject() {
      return function (row) {
        return {
          color: row.true ? "red" : "",
        };
      };
    },
  },
  methods: {
    changeIdentify(e){
      console.log('changeIdentify',e);
    },
    handleSelectAll(e){
      console.log('111',e);
      // this.$refs.Table.clearSelection();
    },
    // datable初始化数据
    initdata() {},
    // 级联选择器改变事件
    handleChange(value) {
      console.log(value);
    },
    // 选中table行的数据
    SelectFun(val) {
      this.selectList = val;
    },
    // 表头的点击事件
    HeaderClick(column, event) {
      // this.$message("成功表头触发事件");
      this.doubleclick = null;
    },
    // 行的双击事件 / 注意:双击事件会触发两次行的单击事件
    RowDblclick(row, column, event) {
      // this.$message("成功双击触发事件");
      this.doubleclick = row.line;
    },
    // 行的单击事件
    RowClick(row, column, event) {
      // this.$message("成功单击触发事件");
      console.log(row, column, event);
      if (this.doubleclick != row.line) {
        this.doubleclick = null;
      }
    },
    // 行编辑按钮
    HandleEdit: function (index, row) {
      //this.$message((index + 1) + '行,你点击了编辑');
      this.doubleclick = row.line;
    },
    // 确认删除按钮[单条数据]
    DeleteData: function (index, rows) {
      //this.deleteTableData.push(rows[index]);
      this.tableData.splice(index, 1);
      this.lineFun(); // 重新计算行索引
    },
    // 表格外的删除按钮[删除多条数据]
    DeleteTableDataFun: function () {
      if (this.selectList.length == 0) {
        this.$message({
          message: "请选择要删除的行",
          type: "warning",
          showClose: true,
        });
      } else {
        var selectList = this.selectList;
        var tableData = this.tableData;
        var deleteTableData = this.deleteTableData;
        this.$confirm("确定要删除选中行数据吗?", "批量删除", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            for (var i in selectList) {
              for (var j in tableData) {
                if (selectList[i].line == tableData[j].line) {
                  deleteTableData.push(tableData[j]);
                  tableData.splice(j, 1);
                }
              }
            }
            this.lineFun(); // 重新计算行索引
          })
          .catch(function (e) {
            console.log(e.message);
          });
        if (tableData) {
          this.tableData = tableData;
          this.deleteTableData = deleteTableData;
        }
      }
    },
    // 删除完成后需要重新计算行的索引字段line
    lineFun: function () {
      for (var i = 0; i < this.tableData.length; i++) {
        this.tableData[i].line = i + 1;
      }
    },
    // 添加一行
    AddRow: function () {
      var data = {
        line: this.tableData.length + 1,
        date: null,
        name: null,
        address: null,
        age: null,
        num: null,
        str1: null,
        str2: null,
        str2laber: null,
        str3: null,
        str4: null,
      };
      this.tableData.push(data);
      this.doubleclick = this.tableData.length;
    },
    // 保存
    SaveData: function () {
      this.$message({
        showClose: true,
        message: JSON.stringify(this.tableData),
        type: "success",
      });
    },
    // 弹出框点击空白不让关闭事件 暂无用
    HandleClose: function () {
      return false;
    },
    handleSizeChange: function (val) {
      console.log("每页 ${val} 条");
    },
    handleCurrentChange: function (val) {
      console.log("当前页: ${val}");
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = sums[index].toFixed(2); // 保留两位小数，解决小数合计列
        } else {
          sums[index] = "/";
        }
      });

      return sums;
    },
    // 日期框的日期格式转换
    DateFormats: function (date) {
      date = new Date(date);
      if (date != null) {
        var ss = typeof date;
        if (ss == "string") {
          return date;
        }
        var fmt = "yyyy-MM-dd";
        var o = {
          "M+": date.getMonth() + 1, //月份
          "d+": date.getDate(), //日
          "h+": date.getHours(), //小时
          "m+": date.getMinutes(), //分
          "s+": date.getSeconds(), //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
          }
        }
        return fmt;
      }
    },
    // 验证字符串是否是数字
    checkNumber(val) {
      let reg = /^\d+(\.\d{1,2})?$/;
      if (reg.test(val)) {
        return true;
      }
      return false;
    },
    async submitForm(formName) {
      const postData = { ...this.form };
      let res;
      try {
        this.loading = true;
        if (this.isCreate) {
          res = "";
        } else {
          res = "";
        }
      } finally {
        this.loading = false;
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // btnEvent,

    btnEvent(btnEvent, index) {
      //eval会将括号内的字符串当作js代码运行
      console.log(btnEvent, index);
      // eval(btnEvent,index);
      switch (btnEvent) {
        case "add":
          add(index);
          break;

        default:
          break;
      }
    },
    add(item) {},
    delete(item) {},
    pickChange(e){
      console.log('change',e);
    },
    pickClick(e){
      console.log('click',e);
    }
  },
};
</script>

<style scoped lang='scss'>
>>> .el-time-spinner__wrapper{
  width: 100% !important;
}
>>> .el-scrollbar:nth-child(2){
  display: none;
}

.el-time-spinner__wrapper{
  width: 100% !important;
}
.el-scrollbar:nth-child(2){
  display: none;
}

.button-desc {
  color: #dc143c;
  font-weight: bold;
  margin-left: 30px;
  font-size: 14px;
}
//  .datepickerPopperClass{
//   .el-button--text{
//     display: none;  //删除时间弹框中此刻按钮(根据需求决定是否保留)
//   }
//   .el-time-spinner__wrapper{
//     width:100%;
//   }
//   .el-scrollbar:nth-child(2){
//     display: none;
//   }
// }

</style>
